import requests
from bs4 import BeautifulSoup
import csv

url = r"https//movie.douban.com/top250"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36"
}

resource = requests.get(url, headers=headers)
soup = BeautifulSoup(resource.text, "html.parser")
movies = soup.find_all("div", class_="info")

with open("douban_top250.csv", 'w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerow(["title", "rating", "comment_num"])
    for movie in movies:
        title = movie.find("span", class_="title").text
        rating = movie.find("span", class_="rating_num").text
        comment_num = movie.find("div", class_="star").find_all("span")[-1].text[:-3]
        writer.writerow([title, rating, comment_num])
